﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace homework5
{
    internal class Program
    {
        static void Main(string[] args)
        {
            GenericList<int> intlist = new GenericList<int>();
            //for(int i=10;i>0;i--)
            //{
            //    intlist.Add(i);
            //}
            Random random = new Random();
            for(int i=0;i<10;i++)
            {
                int randonInt = random.Next(0, 101);
                intlist.Add(randonInt);
            }
            //intlist.Add(10);
            //打印链表
            Console.WriteLine("链表中的元素为：");
            intlist.ForEach(x => {
                Console.Write(x);
                Console.Write(" ");
                });
            Console.WriteLine();
            //用foreach方法求和
            int sum = 0;
            intlist.ForEach(x => sum +=x);
            Console.WriteLine("链表中各元素的和为：" + sum);
            //用foreach方法求最大值
            int maxNum = int.MinValue;
            intlist.ForEach(x =>
            {
                if (x > maxNum) 
                    maxNum = x;
            });
            Console.WriteLine("链表中元素的最大值是：" + maxNum);
            //用foreach方法求最小值
            int minNum = int.MaxValue;
            intlist.ForEach(x =>
            {
                if (x < minNum) minNum = x;
            });
            Console.WriteLine("链表中元素的最小值是：" + minNum);
            Console.ReadKey();
        }
    }
    public class Node<T>
    {
        public Node<T> Next { get; set; }
        public T Data { get; set; }
        public Node(T t)
        {
            Next = null;
            Data = t;
        }
    }
    public class GenericList<T>
    {
        private Node<T> head;
        private Node<T> tail;
        public GenericList()
        {
            tail = head = null;
        }
        public Node<T>Head
        {
            get => head;
        }
        public void Add(T t)
        {
            Node<T> n = new Node<T>(t);
            if(head==null)
            {
                head =tail=n;
            }
            else
            {
                tail.Next = n;
                tail = n;
            }
        }
        public void ForEach(Action<T>action)
        {
            Node<T> current = head;
            while(current!=null)
            {
                action(current.Data);
                current = current.Next;
            }
        }
    }

}
